<template>
    <div class="container flex">
        <div style="width:250px;margin-right: 10px;">
            <n-card class="side">
                <div class="side-top">个人中心</div>
                <n-divider />
                <ul class="side-ul" @click="toggleCard">
                    <li data-name="article" class="side-li active">我的文章</li>
                    <!-- <li data-name="data" class="side-li">数据中心</li> -->
                    <li data-name="collect" class="side-li">我的收藏</li>
                    <li data-name="like" class="side-li">我的点赞</li>
                    <li data-name="guanzhu" class="side-li">我的关注</li>
                    <li data-name="fensi" class="side-li">我的粉丝</li>
                    <li data-name="myMsg" class="side-li">我的信息</li>
                </ul>
                <n-button type="error" size="large" :block="true" style="margin-top: 60px;" @click="logout()">退出</n-button>
            </n-card>
        </div> 
        <div style="flex: 1;">
            <!-- 我的文章 -->
            <n-card v-show="cardType == 'article'">
                <n-tabs 
                  class="card-tabs"
                  default-value="drafts"
                  size="large"
                  type="card"
                  animated
                  style="margin: 0 -4px; width: 100%;"
                  tab-style="color:#333"
                  pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;"
                >
                  <n-tab-pane name="drafts" tab="草稿箱" style="--n-tab-text-color-active:rgb(197, 248, 241);">
                    <n-card >
                        <!-- 卡片组件 -->
                        <articleCard v-for="(item,index) in draftsList" :key="index" :articleItem="item"></articleCard>
                    </n-card>
                  </n-tab-pane>
                  <n-tab-pane name="Published" tab="已发布">
                    <n-card >
                        <!-- 卡片组件 -->
                        <articleCard @click="toArticleDetail(item.id)" v-for="(item,index) in PublishedList" :key="index" :articleItem="item"></articleCard>
                    </n-card>
                  </n-tab-pane>
                  <n-tab-pane name="Audit" tab="待审核">
                    <n-card >
                        <!-- 卡片组件 -->
                        <articleCard  v-for="(item,index) in AuditList" :key="index" :articleItem="item"></articleCard>
                    </n-card>
                  </n-tab-pane>
                  <n-tab-pane name="Failed" tab="未通过">
                    <n-card >
                        <!-- 卡片组件 -->
                        <articleCard v-for="(item,index) in FailedList" :key="index" :articleItem="item"></articleCard>
                    </n-card>
                  </n-tab-pane>
                </n-tabs>
            </n-card>
            <!-- 数据中心 -->
            <n-card v-show="cardType == 'data'">
                <n-grid x-gap="12" :cols="3">
                  <n-gi>
                    <div class="grid-card" >
                        <h2>总关注者数</h2>
                        <h1>0</h1>
                    </div>
                  </n-gi>
                  <n-gi>
                    <div class="grid-card" >
                        <h2>文章展现数</h2>
                        <h1>0</h1>
                    </div>
                  </n-gi>
                  <n-gi>
                    <div class="grid-card" >
                        <h2>文章阅读数量</h2>
                        <h1>0</h1>
                    </div>
                  </n-gi>
                  <n-gi>
                    <div class="grid-card" >
                        <h2>文章点赞数</h2>
                        <h1>0</h1>
                    </div>
                  </n-gi>
                  <n-gi>
                    <div class="grid-card" >
                        <h2>文章评论数</h2>
                        <h1>0</h1>
                    </div>
                  </n-gi>
                  <n-gi>
                    <div class="grid-card" >
                        <h2>文章收藏数</h2>
                        <h1>0</h1>
                    </div>
                  </n-gi>
                </n-grid>
            </n-card>
            <!-- 我的收藏 -->
            <n-card v-show="cardType == 'collect'">
                <articleCard @click="toArticleDetail(item.id)" v-for="(item,index) in collectList" :key="index" :articleItem="item.articleMsg"></articleCard>
            </n-card>
            <!-- 我的点赞 -->
            <n-card v-show="cardType == 'like'">
                <articleCard @click="toArticleDetail(item.id)" v-for="(item,index) in likeList" :key="index" :articleItem="item.articleMsg"></articleCard>
            </n-card>
            <!-- 我的关注 -->
            <n-card v-show="cardType == 'guanzhu'">
                <n-grid x-gap="12" :cols="4" >
                    <n-gi v-for="(item,index) in guanzhuList" :key="index">
                        <n-card>
                            <div class="flex at-center">
                                <img  :src="globalProperties.$imgServer+item.avatar" alt="" style="width: 60px;height: 60px;border-radius: 50%;margin-right: 15px;">
                                <div class="flex" style="align-items: center;flex-direction: column;">
                                    <h3 class="mr10">{{item.username}}</h3>
                                    <n-button class="mt10" size="small">取消关注</n-button>
                                </div>
                            </div>
                        </n-card>
                    </n-gi>
                </n-grid>
            </n-card>
            
            <!-- 我的粉丝 -->
            <n-card v-show="cardType == 'fensi'">
                <n-grid x-gap="12" :cols="4" >
                    <n-gi v-for="(item,index) in fensiList" :key="index">
                        <n-card>
                            <div class="flex at-center">
                                <img  :src="globalProperties.$imgServer+item.avatar" alt="" style="width: 60px;height: 60px;border-radius: 50%;margin-right: 15px;">
                                <div class="flex" style="align-items: center;flex-direction: column;">
                                    <h3 class="mr10">{{item.username}}</h3>
                                </div>
                            </div>
                        </n-card>
                    </n-gi>
                </n-grid>
            </n-card>
            <!-- 我的信息 -->
            <div v-show="cardType== 'myMsg'" class="flex">
                <n-card >
                    <div class="flex at-center j-sb" style="width: 100%; border-bottom: 1px solid #f2f2f2;padding: 10px 0;">
                        <div style="width: 80px;height: 80px;"><img style="border: 2px solid ; width: 100%;height: 100%; border-radius: 50%;" :src="avatar" alt="" ></div>
                        <div>
                            <n-upload :file-list-style="{'display':'none'}"   :action="`http://127.0.0.1:7001/admin/file`" @finish="handleFinish"  accept="image/png, image/jpeg">
                                <MyButton height="30px" width="100px">修改头像</MyButton>
                            </n-upload>
                        </div>
                    </div>
                    <div class="flex at-center j-sb" style="padding: 10px 0;border-bottom: 1px #f2f2f2 solid;" >
                        <div class="flex at-center">
                          <svg-icon :className="'msg-icon'"  iconName="icon-db_mgdb_user-copy"></svg-icon>
                          <span v-if="!consoleUsername" style="font-size: 20px;margin-left: 10px;">{{ userInfo.username }}</span>
                          <n-input v-if="consoleUsername" v-model:value="newUsername" placeholder="请输入新的用户名" ></n-input>
                        </div>
                        <div class="flex">
                            <MyButton v-if="!consoleUsername" height="30px" width="100px" @click="updateUsername()">修改用户名</MyButton>
                            <n-button @click="confirmUsername()" v-if="consoleUsername" style="background-color: aquamarine;" class="mr10">确认</n-button>
                            <n-button @click="cencelUsername()" v-if="consoleUsername">取消</n-button>
                        </div>
                    </div>
                    <div class="flex at-center j-sb" style="padding: 10px 0;border-bottom: 1px #f2f2f2 solid;" >
                        <div class="flex at-center">
                            <svg-icon :className="'msg-icon'"  iconName="icon-yuechi"></svg-icon>
                            <span v-if="!consolePassword" style="font-size: 20px;margin-left: 10px;">*******</span>
                            <div v-if="consolePassword" style="width:50%;margin-left: 15px;">
                                <n-input type="password" v-model:value="oldPassword" placeholder="请输入原密码" ></n-input>
                                <n-input type="password" v-model:value="newPassword" placeholder="请输入新密码" class="mt10"></n-input>
                            </div>

                        </div>

                        <div class="flex">
                            <MyButton v-if="!consolePassword" height="30px" width="100px" @click="updatePassword()">修改密码</MyButton>
                            <n-button @click="confirmPassword()" v-if="consolePassword" style="background-color: aquamarine;" class="mr10">确认</n-button>
                            <n-button @click="cencelPassword()" v-if="consolePassword">取消</n-button>
                        </div>
                    </div>
                </n-card>
                <n-card title="其他信息">
                    <MyButton v-if="!consoleOther" height="30px" @click="updateOther()">编辑</MyButton>
                    <div v-if="!consoleOther" style="font-size: 18px;margin-top: 10px;">昵称：{{ userInfo.nickname }}</div> 
                    <div v-if="!consoleOther" style="font-size: 18px;margin-top: 10px;">性别：{{ userInfo.gender==1?'男':userInfo.gender == 2?'女':'未知' }}</div> 
                    <div v-if="!consoleOther" style="font-size: 18px;margin-top: 10px;">简介：{{ userInfo.introduction }}</div>
                    <n-input  v-if="consoleOther" v-model:value="newPassword" placeholder="请输入新昵称" class="mt10"></n-input>
                    <n-select v-if="consoleOther"  v-model:value="newGender"  class="mt10" :options="genderOption"></n-select>
                    <n-input  v-if="consoleOther" type="textarea" v-model:value="newPassword" placeholder="请输入简介" class="mt10"></n-input>
                    <div class="flex mt10" v-if="consoleOther">
                        <n-button @click="confirmOther()"  style="background-color: aquamarine;" class="mr10">确认</n-button>
                        <n-button @click="cencelOther()">取消</n-button>
                    </div>
                </n-card>
            </div>
            
        </div>
    </div>
</template>

<script setup lang="ts">
    import requestList from '@/service/request';
    import { getItem ,removeItem} from '@/utils/local';
    import type { UploadFileInfo } from 'naive-ui'
    import {useRouter} from 'vue-router'
    import { ref,onMounted,getCurrentInstance } from 'vue';
    import { useUserInfoStore,useAuthStore } from '@/store/main'
import MyButton from '@/components/myButton.vue';
    const userInfo = ref(getItem('curUserInfo'))
    const authStore = useAuthStore()
    const router = useRouter()
    const userStore = useUserInfoStore()
    
    const { appContext : { config: { globalProperties } } } = (getCurrentInstance() as any)
    const avatar = ref(globalProperties.$imgServer+userInfo.value.avatar) 
    const cardType = ref('article')

    const toggleCard = (e:any)=>{
        console.log(e);
        
        for(let i = 0;i<e.target.parentNode.children.length;i++){
            e.target.parentNode.children[i].classList.remove('active')
        }
        e.target.classList.add('active')
        cardType.value =  e.target.attributes['data-name'].value
    }

    // 文章草稿
    const draftsList = ref([]) //草稿 0
    const PublishedList = ref([]) //审核通过（已发布）2
    const AuditList = ref([]) //待审核 1 
    const FailedList = ref([]) //未通过 3
    
    

    //标签列表
    const tagsList =ref<any[]>([])
    const getTags = async () =>{
        const res = await requestList.tagListApi({all:true})
        if(res.code === 1){
            tagsList.value = res.data as any
        }
    }

    //话题列表
    const topicList = ref<any[]>([])
    const getTopic = async ()=>{
        const res = await requestList.topicListApi({all:true})
        if(res.code === 1){
            topicList.value = res.data as any
        }
    }

    // 获取文章
    const getAllArticlesbyUser = async () =>{
        const res = await requestList.articleListApi({allType:true,user_id:userInfo.value.id})
        if(res.code === 1){
            (res.data as any).forEach((item:any)=>{
                let tagsName:string[] = []
                let topicName:string[] = []
                let tagIds = item.tags.split(',')
                let topicIds = item.topic.split(',')
                tagsList.value.forEach((x:any)=>{
                    tagIds.forEach((y:any)=>{
                        if(x.id === Number(y)){
                            tagsName.push(x.tag_name)
                        }
                    })
                })
                topicList.value.forEach((x:any)=>{
                    topicIds.forEach((y:any)=>{
                        if(x.id === Number(y)){
                            topicName.push(x.topic_name)
                        }
                    })
                })
                item.tagsName = tagsName
                item.topicName = topicName
            })
            draftsList.value = (res.data as any).filter((item:any)=>(item.status === 0))
            AuditList.value = (res.data as any).filter((item:any)=>(item.status === 1))
            PublishedList.value = (res.data as any).filter((item:any)=>(item.status === 2))
            FailedList.value = (res.data as any).filter((item:any)=>(item.status === 3))
        }
    }

    // 获取全部文章
    const allArticleList = ref<any[]>([])
    const getAllArticles = async () =>{
        const res = await requestList.articleListApi({all:true})
        if(res.code === 1){
            allArticleList.value = (res.data as any) 
        }
    }

    // 获取点赞列表
    const likeList = ref<any[]>([])
    const getlikes = async ()=>{
        const res = await requestList.likeArticleListByUserApi({user_id:userInfo.value.id})
        if(res.code === 1){
            likeList.value = (res.data as any)
            likeList.value.forEach((item:any)=>{
                allArticleList.value.forEach((data:any)=>{
                    if(item.article_id == data.id){
                        item.articleMsg = data
                    }
                })
            })
            console.log(likeList.value);
            
        }
    }
    
    // 获取收藏列表
    const collectList = ref<any[]>([])
    const getCollects = async ()=>{
        const res = await requestList.collectListByUserApi({user_id:userInfo.value.id})
        if(res.code === 1){
            collectList.value = (res.data as any)
            collectList.value.forEach((item:any)=>{
                allArticleList.value.forEach((data:any)=>{
                    if(item.article_id == data.id){
                        item.articleMsg = data
                    }
                })
            })
            
        }
    }

    // 关注-粉丝
    const guanzhuList = ref<any[]>([]) // 关注列表
    const fensiList = ref<any[]>([]) // 粉丝列表
    
    const getGuanzhuList = async () => {
        const postData = {
            type:1,
            all:true,
            user_id:userInfo.id
        }
        const res = await requestList.subscribeByUserApi(postData)
        if(res.code === 1){
            guanzhuList.value = res.data as any
        }
    }
    const getFensiList = async () => {
        const postData = {
            type:2,
            all:true,
            user_id:userInfo.id
        }
        const res = await requestList.subscribeByUserApi(postData)
        if(res.code === 1){
            fensiList.value = res.data as any
        }
    }

    // 退出
    const logout = () => {
        removeItem('curUserInfo')
        removeItem('token')
        authStore.myToken = ''
        authStore.refreshToken = ''
        userStore.userInfo = ''
        router.push('/login')
    }

    // 跳转详情页
    const toArticleDetail = (id:number) => {
        router.push({path:'/articleDetails',query:{id}})
    }
    // 上传
    const handleFinish =  async ({file,event}: {
      file: UploadFileInfo
      event?: ProgressEvent
    })=>{
        const res = await requestList.updateAvatarApi({
            id:userInfo.value.id,
            avatar:`${JSON.parse((event?.target as XMLHttpRequest).response).data[0].url}`
        })
        if(res.code === 1){
            userStore.getUserInfo()
        }
        avatar.value = `http://127.0.0.1:7001/public${JSON.parse((event?.target as XMLHttpRequest).response).data[0].url}`
    }

    const consoleUsername = ref(false)
    const consolePassword = ref(false)
    const consoleOther = ref(false)

    const newUsername = ref('')
    const updateUsername = ()=>{
        consoleUsername.value = true
        newUsername.value = userInfo.value.username
    }

    const oldPassword = ref('')
    const newPassword = ref('')
    const updatePassword = ()=>{
        consolePassword.value = true
    }

    const newNickname = ref('')
    const newGender = ref(null)
    const genderOption = ref<any[]>([
        {label:'男',value:1},
        {label:'女',value:2},
        {label:'未知',value:0},
    ])
    const newIntroduction = ref('')
    const updateOther = () => {
        consoleOther.value = true
        newIntroduction.value = userInfo.value.introduction
        newNickname.value = userInfo.value.nickname
        newGender.value = userInfo.value.gender
    }

    const confirmUsername = async ()=>{
        if(newUsername.value.trim()===''){
            window.$message.warning('请输入新用户名')
            return
        }
        const postData = {
            id:userInfo.value.id,
            username:newUsername.value
        }
        const res = await requestList.updateUsernameApi(postData)
        if(res.code === 1){
            userStore.getUserInfo()
            cencelUsername()
            userInfo.value = getItem('curUserInfo')
        }
    }
    const cencelUsername = ()=>{
        consoleUsername.value = false
        newUsername.value = ''
    }

    const confirmPassword = async ()=>{
        if(oldPassword.value.trim()===''){
            window.$message.warning('请输入原密码')
            return
        }
        if(newPassword.value.trim()===''){
            window.$message.warning('请输入新密码')
            return
        }
        const postData = {
            id:userInfo.value.id,
            oldPassword,newPassword
        }
        const res = await requestList.updatePsdApi(postData)
        if(res.code === 1){
            userStore.getUserInfo()
            userInfo.value = getItem('curUserInfo')
            cencelPassword()
        }else{
            window.$message.warning('原密码错误')
        }
    }
    const cencelPassword = ()=>{
        oldPassword.value = ''
        newPassword.value = ''
        consolePassword.value = false
    }

    const confirmOther = async ()=>{
        if(newNickname.value.trim()===''){
            window.$message.warning('请输入昵称')
            return
        }
        if(newGender.value.trim() == null){
            window.$message.warning('请选择性别')
            return
        }
        const postData = {
            id:userInfo.value.id,
            gender:newGender.value,
            introduction:newIntroduction.value,
        }
        const res = await requestList.updateOtherMsgApi(postData)
        if(res.code === 1){
            userStore.getUserInfo()
            userInfo.value = getItem('curUserInfo')
            cencelOther()
        }
    }

    const cencelOther = ()=>{
        consoleOther.value = false
        newIntroduction.value = ''
        newNickname.value = ''
        newGender.value = null
    }
    

    onMounted(async ()=>{
        await getTags()
        await getTopic()
        await getAllArticles()
        await getAllArticlesbyUser()
        await getlikes()
        await getCollects()
        await getGuanzhuList()
        await getFensiList()
    })
</script>

<style lang="scss" scoped>
.side{
    &-top{
        font-weight: 600;
        font-size: 16px;
        line-height: 36px;
        height: 40px;
        border: 2px solid ;
        text-align: center;
        border-radius: 6px;
        background-color: $color3;
    }
    &-ul{
        li{
            user-select: none;
            font-size: 16px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            cursor: pointer;
            margin-bottom: 10px;
            transition: all .3s ;
            &:hover{
                background-color: $color3;
                border-radius: 5px;
                font-weight: 600;
                font-size: 18px;
            }
        }
        .active{
            background-color: $color3;
            border-radius: 5px;
            font-weight: 600;
            font-size: 18px;
        }
    }
}

.grid-card{
    margin-top: 10px;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    background-color: #f2f2f2;
}
.msg-icon{
    width: 24px;
    height: 24px;
}


</style>